package com.easy.carl.algorithm.array.slidingWindow;

import java.util.HashMap;

/**
 * @ClassName TotalFruit904
 * @Description 904. 水果成篮
 * @Author zheng
 * @Date 2021/12/15 15:10
 * @Version 1.0
 **/
public class TotalFruit904 {
    /**
     * @return
     * @Description 暴力法
     * @Date 2021/12/15 16:31
     * @Param
     **/
    public int totalFruit1(int[] fruits) {
        //最多可收集水果数
        int maxNum = 0;
        for (int i = 0; i < fruits.length; i++) {
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int j = i; j < fruits.length; j++) {
                map.put(fruits[j], fruits[j]);
                if (map.size() <= 2) {
                    maxNum = Math.max(maxNum, j - i + 1);
                } else {
                    break;
                }
            }
        }
        return maxNum;
    }

    /**
     * @return int
     * @Description 滑动窗口
     * @Date 2021/12/15 16:22
     * @Param [fruits]
     **/
    public int totalFruit(int[] fruits) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int len = fruits.length;
        //窗口左边界和右边界
        int left = 0, right = 0;
        //最大值
        int maxNum = 0;
        while (right < len) {
            //将右边界的值放入map 中存储起来
            map.put(fruits[right], map.getOrDefault(fruits[right], 0) + 1);
            //当map.size小于2时，表示一直满足条件，记录此时的最大值
            if (map.size() <= 2) {
                maxNum = Math.max(maxNum, right - left + 1);
            }
            //map 长度大于2
            while (map.size() > 2) {
                //收缩左边界，直至不大于2
                map.put(fruits[left], map.getOrDefault(fruits[left], 0) - 1);
                if (map.getOrDefault(fruits[left], 0) == 0) {
                    map.remove(fruits[left]);
                }
                left++;
            }
            right++;
        }
        return maxNum;
    }


    public static void main(String[] args) {
        TotalFruit904 totalFruit904 = new TotalFruit904();
        System.out.println(totalFruit904.totalFruit(new int[]{0, 1, 2, 2}));
    }
}
